package com.eystar.pdc.controller;

import javax.servlet.http.HttpSession;

import com.eystar.ext.route.ControllerBind;
import com.eystar.pdc.aop.auth.AuthAnno;
import com.eystar.pdc.aop.auth.AuthAnno.AuthType;
import com.eystar.pdc.aop.log.LogAnno;
import com.eystar.pdc.aop.log.LogAnno.LogType;
import com.eystar.pdc.model.DicItem;
import com.eystar.pdc.model.Login;
import com.eystar.pdc.model.User;
import com.eystar.pdc.util.LoginUtil;
import com.eystar.pdc.util.PdcHelper;
import com.jfinal.captcha.CaptchaRender;
import com.jfinal.kit.Ret;

import cn.hutool.core.util.StrUtil;

@ControllerBind(controllerKey = "/login", viewPath = "/pdc")
@AuthAnno(type = AuthType.AnyOne)
public class LoginController extends BaseController {

	/**
	 * 跳转到登陆页页面。如果已经登录的话，直接跳转到首页
	 * 
	 * @throws Exception
	 */
	public void index() throws Exception {
		// 如果 用户没有登录
		if(PdcHelper.hasLogin(getRequest())){
			render("login.html");
			return;
		}
		// 1、从字典中配置登录成功跳转的路径
		String redirectUrl = DicItem.dao.findDicItemValue("system", "login_success_url");;
		// 2、进行跳转
		if (StrUtil.isBlank(redirectUrl)) {
			redirectUrl = "/";
		}
		redirect(redirectUrl);
		
	}

	/**
	 * 登录操作
	 * 
	 * @throws Exception
	 */
	@LogAnno(desc = "用户登录", type = LogType.LOGIN)
	public void doLogin() throws Exception {
		try {
			Ret ret = ok();
			// 是否启用验证码
			String verification = DicItem.dao.findDicItemValue("system", "verification");
			if(StrUtil.equals(verification, "0")){
				ret = Login.dao.login(getRequest(), getModel(User.class));
			}else if (CaptchaRender.validate(this, getPara("inputRandomCode"))) {
				ret = Login.dao.login(getRequest(), getModel(User.class));
			}else {
				ret = fail("验证码不正确！");
			}
			renderJson(ret);
		} catch (Exception e) {
			logger.error("登录异常！", e);
			renderJson(fail());
		}
	}
	
	/**
	 * 用户退出
	 * @throws Exception
	 */
	@LogAnno(desc = "用户退出", type = LogType.LOGIN)
	public void logout() throws Exception {
		try {
			HttpSession session = getSession();
			session.removeAttribute(LoginUtil.SESSION_CURRENT_USER);
			session.invalidate();
			session.setMaxInactiveInterval(0);
		} catch (Exception e) {
			logger.error("退出异常！", e);
		} finally {
			redirect("/login");
		}
	}
	
	/**
	 * 刷新验证码
	 */
	public void refreshCaptcha(){
		render(new CaptchaRender());
	}
	
}
